//https://leetcode.cn/problems/dungeon-game/description/
//地下城游戏

class Solution {
public:
    int calculateMinimumHP(vector<vector<int>>& dungeon) {
        int m = dungeon.size();
        int n = dungeon[0].size();

        int dp[m][n];
        dp[m - 1][n - 1] = max(-dungeon[m - 1][n - 1], 0);
        for(int i = m - 2; i >= 0; --i)
        {
            dp[i][n - 1] = max(dp[i + 1][n - 1] - dungeon[i][n - 1], 0);
        }
        for(int j = n - 2; j >= 0; --j)
        {
            dp[m - 1][j] = max(dp[m - 1][j + 1] - dungeon[m - 1][j], 0); 
        }

        for(int i = m - 2; i >= 0; --i)
        {
            for(int j = n - 2; j >= 0; --j)
            {
                dp[i][j] = min(dp[i + 1][j], dp[i][j + 1]) - dungeon[i][j];
                dp[i][j] = max(dp[i][j], 0);
            }
        }

        return dp[0][0] + 1;
    }
};